from django.contrib.auth.backends import ModelBackend
import re

from users.models import User


class MyBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None):
        # 1. 判断username 是不是手机号格式,如果是的话根据手机号取用户
        try:
            if re.match(r'1[345789]\d{9}', username):
                user = User.objects.get(mobile=username)
            # 2. 如果不是, 根据用户名取用户
            else:
                user = User.objects.get(username=username)
        except Exception as e:
            return None
        # 3. 判断密码是否正确  # 4. 返回用户, 或者 None
        if user.check_password(raw_password=password):
            return user
        else:
            return None
